package com.spring.Service;

import com.spring.Entity.UserEntity;
import com.spring.Repository.UserRepository;
import com.spring.Service.Interface.UserServie;
import com.spring.Util.JavaMail;
import com.spring.Util.MD5Util;
import com.spring.Util.STATUS;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Arabira on 2016/8/3.
 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserServie {
    @Autowired
    private UserRepository userRepository;

    private Map<String, Object> response;

    @Override
    public String login(String userName, String password) {
        UserEntity userEntity = findByUserName(userName);
        if (userEntity == null) {
            return "用户不存在";
        }
        if (!userEntity.getPassword().equals(password)) {
            return "密码错误";
        } else {
            return null;
        }
    }

    @Override
    public int addUser(UserEntity userEntity) {
        userEntity.setPassword(MD5Util.calc(userEntity.getPassword()));
        userRepository.save(userEntity);
        return STATUS.SUCCESS;
    }

    @Override
    public int updateUser(UserEntity userEntity, String oa, String emailAddress) {
        int status = 1;
        if (!StringUtils.isBlank(oa)) {
            if (JavaMail.checkMailAddress(oa)) {
                userEntity.setOa(oa);
                status = STATUS.SUCCESS;
            } else {
                status = STATUS.FORMAT_ERROR;
            }
        }
        if (!StringUtils.isBlank(emailAddress)) {
            if (JavaMail.checkMailAddress(emailAddress)) {
                userEntity.setEmailAddress(emailAddress);
                status = STATUS.SUCCESS;
            } else {
                status = STATUS.FORMAT_ERROR;
            }
        }
        userRepository.saveAndFlush(userEntity);
        return status;
    }

    @Override
    public UserEntity findById(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        } else {
            return userRepository.findOne(userId);
        }
    }

    @Override
    public UserEntity findByUserName(String userName) {
        if (StringUtils.isBlank(userName)) {
            return null;
        } else {
            return userRepository.findOneByUserName(userName);
        }
    }

    @Override
    public int changePassword(String userId, String oldPassword, String newPassword) {
        Map<String, Object> response = new HashMap<>();
//        oldPassword = MD5Util.calc(oldPassword);
//        newPassword = MD5Util.calc(newPassword);
        UserEntity userEntity = findById(userId);

        if (!userEntity.getPassword().equals(oldPassword)) {
            return STATUS.FAIL;
        } else {
            userEntity.setPassword(newPassword);
            userRepository.saveAndFlush(userEntity);
            return STATUS.SUCCESS;
        }
    }

    public String genRandom3() {
        return ((int) (Math.random() * 900) + 100) + "";
    }

    //从excel表格添加用户
    @Override
    public String addByExcel(MultipartFile file) throws IOException, BiffException {
        String message;
        File file1 = new File("ContractMSTemp");
        FileOutputStream fileOutputStream = new FileOutputStream(file1);
        BufferedOutputStream outputStream = new BufferedOutputStream(fileOutputStream);
        outputStream.write(file.getBytes());
        Workbook workbook = Workbook.getWorkbook(file1);
        Sheet sheet = workbook.getSheet(0);
        int row = sheet.getRows();
        for (int i = 1; i < row; i++) {
            Cell cell = null;
            UserEntity userEntity = new UserEntity();
            //员工编号
            if (null != (cell = sheet.getCell(0, i)) && !StringUtils.isBlank(cell.getContents())) {
                userEntity.setId(System.currentTimeMillis() + genRandom3());
            } else {

                message = "第" + (i+1) + "行：员工编号不为空";
                return message;
            }
            //用户名
            if (null != (cell = sheet.getCell(1, i)) && !StringUtils.isBlank(cell.getContents())) {
                UserEntity checkdup = userRepository.findOneByUserName(cell.getContents());
                if(checkdup!=null){
                    message = "员工编号"+cell.getContents()+"重复！";
                    return message;
                }
                userEntity.setUserName(cell.getContents());
            } else {

                message = "第" + (i+1) + "行：用户名不为空";
                return message;
            }
            if ((null != (cell = sheet.getCell(2, i))) && (!StringUtils.isBlank(cell.getContents()))) {
                userEntity.setPassword(MD5Util.calc(cell.getContents()));
            } else {

                message = "第" + (i+1) + "行：密码不为空";
                return message;
            }
            //姓名
            if (null != (cell = sheet.getCell(3, i)) && !StringUtils.isBlank(cell.getContents())) {
                userEntity.setName(cell.getContents());
            } else {

                message = "第" + (i+1) + "行：姓名不为空";
                return message;
            }
            //职位
            if (null != (cell = sheet.getCell(4, i)) && !StringUtils.isBlank(cell.getContents())) {
                userEntity.setDepartment(cell.getContents());
            } else {

                message = "第" + (i+1) + "行：职位不为空";
                return message;
            }
            //电话
            userEntity.setPhone(sheet.getCell(5, i).getContents());
            //139邮箱
            userEntity.setEmailAddress(sheet.getCell(6, i).getContents());
            //OA邮箱
            userEntity.setOa(sheet.getCell(7, i).getContents());
            userEntity.setStatus("1");
            if (checkUser(userEntity))
                userRepository.saveAndFlush(userEntity);
        }
        return null;
    }

    //检查用户是否存在，存在返回false，不存在返回true
    @Override
    public Boolean checkUser(UserEntity userEntity) {
        UserEntity check = null;
        if (!StringUtils.isBlank(userEntity.getId())) {
            check = userRepository.findOne(userEntity.getId());
        } else if (!StringUtils.isBlank(userEntity.getUserName())) {
            check = userRepository.findOneByUserName(userEntity.getUserName());
        }
        if (check == null) {
            return true;
        } else
            return false;
    }

    @Override
    public Map<String, Object> findUsersAll() {
        response = new HashMap<>();

        UserEntity[] page = userRepository.findUsersAll();

        response.put("status", "ok");
        response.put("body", page);

        return response;

    }

    @Override
    public Map<String, Object> findReqUsersAll(UserEntity userEntity) {
        response = new HashMap<>();
        userEntity.setUserName((userEntity.getUserName() != null) ? "%" + userEntity.getUserName() + "%" : "");
        userEntity.setName((userEntity.getName() != null) ? "%" + userEntity.getName() + "%" : "");
        userEntity.setDepartment((userEntity.getDepartment() != null) ? "%" + userEntity.getDepartment() + "%" : "");


        UserEntity[] page = userRepository.findReqUsersAll(userEntity.getUserName(), userEntity.getName(), userEntity.getDepartment());

        if (page.length == 0) {
            response.put("status", "datanull");
        } else {
            response.put("status", "ok");
            response.put("body", page);
        }


        return response;
    }

    @Override
    public UserEntity findByUserId(String userId) {
        if (StringUtils.isBlank(userId)) {
            return null;
        } else {
            return userRepository.findOne(userId);
        }
    }


    @Override
    public int updateUserByAdmin(UserEntity userEntity) {
        int status = 1;
        String oa = userEntity.getOa();
        String emailAddress = userEntity.getEmailAddress();
        if (!StringUtils.isBlank(oa)) {
            if (JavaMail.checkMailAddress(oa)) {
                userEntity.setOa(oa);
                status = STATUS.SUCCESS;
            } else {
                status = STATUS.FORMAT_ERROR;
            }
        }
        if (!StringUtils.isBlank(emailAddress)) {
            if (JavaMail.checkMailAddress(emailAddress)) {
                userEntity.setEmailAddress(emailAddress);
                status = STATUS.SUCCESS;
            } else {
                status = STATUS.FORMAT_ERROR;
            }
        }
        userRepository.saveAndFlush(userEntity);
        return status;
    }

    @Override
    public int changePassByAdmin(String userId, String newPassword) {
        Map<String, Object> response = new HashMap<>();

//        newPassword = MD5Util.calc(newPassword);
        UserEntity userEntity = findById(userId);
        userEntity.setPassword(newPassword);
        userRepository.saveAndFlush(userEntity);
        return STATUS.SUCCESS;
    }
}